/*--------------------------------------------------------------------*
 * Read a photocell connected to an analog pin.  The reading          *
 * returned is the moving average of the last six readings, so the    *
 * assumption is that this function is called periodically.           *
 *                                                                    *
 * J. Christensen 25Feb2011                                           *
 *--------------------------------------------------------------------*/
int readPhotocell(int pcPin) {

    static boolean first = true;    //first-time flag
    static int reading, readings[6];
    int avg = 0;
    
    reading = analogRead(pcPin);    //read the photocell

    if (first) {                    //fill the readings array on the first time through
        first = false;
        for (int i=0; i<6; i++) {
            readings[i] = reading;
        }
    }
    for (int i=0; i<5; i++) {       //shift prior readings
        readings[i] = readings[i+1];
    }
    readings[5] = reading;          //put the new reading in at the top end of the array
    for (int i=0; i<6; i++) {       //calculate the average
        avg += readings[i];
    }
    avg = (avg + 3) / 6;
    return avg;
}
